package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.IApUnlikeBehaviorService;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dto.BehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUnlikeBehaviorServiceImpl implements IApUnlikeBehaviorService {

    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult unlike(BehaviorDto dto) {
        // 1. 检查参数
        if (dto == null || dto.getArticleId() == null || checkParam(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3. 不喜欢 保存数据
        String key = "UNLIKE-BEHAVIOR-" + dto.getArticleId().toString();
        String hashKey = user.getId().toString();
        if (dto.getType() == 0){
            Object object = cacheService.hGet(key, hashKey);
            if (object != null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "禁止重复操作");
            }
            // 保存key
            log.info("保存数据：{}，{}，{}", key, hashKey, JSON.toJSONString(dto));
            cacheService.hPut(key, hashKey, JSON.toJSONString(dto));
        }else {
            log.info("删除数据：{}，{}", key, hashKey);
            cacheService.hDelete(key, hashKey);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private boolean checkParam(BehaviorDto dto) {
        return dto.getType() < 0 || dto.getType() > 1;
    }
}
